package com.yaxin.job.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * @author lguoji
 */
@Slf4j
public class MySQLBackupUtils {

    /**
     * 执行备份
     */
    public static void backup(File file, String ip, String user, String password, String dbTable) {
        try {
            String command = String.format(" mysqldump --single-transaction -h%s -u%s -p%s --set-charset=utf8 %s",
                ip, user, password, dbTable);
            log.info(">>>>>>>>>>> 数据库备份执行命令为：{}", command);
            Process process = Runtime.getRuntime().exec(command);
            InputStream inputStream = process.getInputStream();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                 OutputStreamWriter writer = new OutputStreamWriter(Files.newOutputStream(file.toPath()), StandardCharsets.UTF_8)) {
                String line;
                while ((line = reader.readLine()) != null) {
                    writer.write(line + System.lineSeparator());
                }
                writer.flush();
            }
            inputStream.close();
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                printError(process.getErrorStream());
                throw new RuntimeException("备份失败，退出码：" + exitCode);
            }
        } catch (Exception e) {
            log.error(">>>>>>>>>>> 数据库备份失败！", e);
            throw new RuntimeException(e);
        }

        log.info(">>>>>>>>>>> MySQL数据库备份成功,数据库：{}", dbTable);
    }

    /**
     * 打印错误输出
     */
    private static void printError(InputStream errorStream) throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                log.error("备份错误输出: {}", line);
            }
        }
    }

    /**
     * 清理 N 天前的备份文件
     */
    public static void cleanOldFiles(String dirPath, int days) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            return;
        }

        long cutoff = System.currentTimeMillis() - days * 24L * 60 * 60 * 1000;
        File[] files = dir.listFiles((f) -> f.isFile() && f.getName().endsWith(".sql") && f.lastModified() < cutoff);
        if (files != null) {
            for (File file : files) {
                boolean deleted = file.delete();
                log.info(">>>>>>>>>>> 清理旧备份文件 [{}]: {}", file.getName(), deleted ? "成功" : "失败");
            }
        }
    }
}

